package com.ztgf.sys.api.cms;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.common.constant.Result;
import com.ztgf.common.constant.ZTConstant;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.AESUtil;
import com.ztgf.common.utils.Md5Utils;
import com.ztgf.common.utils.SignUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.sys.api.common.annotion.SysLogs;
import com.ztgf.sys.models.bo.SysUserBO;
import com.ztgf.sys.models.bo.SysUserSaveBO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.sys.models.service.ISysUserRoleRelationService;
import com.ztgf.sys.models.service.ISysUserService;
import com.ztgf.sys.models.vo.SysRoleVO;
import com.ztgf.sys.models.vo.SysUserKeyVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户表控制器
 *
 * @author YUE
 * @Date 2020-05-27 15:01:09
 */

@RestController
@RequestMapping("/cms/sysUser")
@Slf4j
@Api(value = "SysUserController",tags = "系统用户表接口")
public class SysUserController {

    @DubboReference
    private ISysUserService sysUserService;

    @DubboReference
    private ISysUserRoleRelationService sysUserRoleRelationService;

    @PostMapping("/getRoleIdTreeListByUserId")
    @ApiOperation(value = "根据用户id获取角色 树",notes = "根据用户id获取角色 树")
    public Result<SysRoleVO> getRoleIdTreeListByUserId(Long userId){
        if(null == userId){
            return  new Result(CodeEnum.FAIL_100002);
        }
        return new Result(sysUserRoleRelationService.getRoleIdTreeListByUserId(userId));
    }

    /**
     * 重置密码
     * @param newPw 新密码
     * @return
     */
    @SysLogs(value = "重置用户密码")
    @ApiOperation(value = "重置密码",notes = "重置密码")
    @PostMapping(value = "/updateResetPwById")
    public Result updateResetPwById(String newPw){
        if(newPw == null){
            return new Result<>(CodeEnum.FAIL_LOGIN_2004 );
        }
        return sysUserService.resetPw(newPw);
    }

    @SysLogs(value = "修改用户信息")
    @ApiOperation(value = "修改系统用户表",notes = "修改系统用户表")
    @PostMapping("/update")
    public Result update(SysUserSaveBO saveBO,String password){
        Long id = saveBO.getId();
        if(null == id){
            return new Result(CodeEnum.FAIL_USER_200003);
        }
        SysUserDTO sysUserDTO = sysUserService.selectById(id);
        if(null == sysUserDTO){
            return new Result(CodeEnum.FAIL_USER_200003);
        }
        sysUserDTO.setName(saveBO.getName());
        sysUserDTO.setAccount(saveBO.getAccount());
        sysUserDTO.setMobile(saveBO.getMobile());
        sysUserDTO.setPassword(Md5Utils.MD5Encode(password.toLowerCase(),sysUserDTO.getSalt()));
        boolean flag = sysUserService.updateById(sysUserDTO);
        if (flag){
            //去除session
            sysUserService.resetSession(id);
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    /**
     *
     * 修改密码 根据旧密码
     *
     * @param newPw 新密码
     * @param authCode 验证码
     * @return
     */
    @SysLogs(value = "修改密码")
    @ApiOperation(value = "修改密码根据旧密码",notes = "修改密码根据旧密码")
    @PostMapping(value = "/updatePwByMobile")
    public Result updatePwByOldPwAndId(String newPw, String authCode){
        if(StrUtils.isEmpty(newPw))
            return new Result<>(CodeEnum.FAIL_LOGIN_2004 );
        return sysUserService.updatePwByOldPwAndId(newPw,authCode);
    }

    @SysLogs(value = "新增系统用户")
    @ApiOperation(value = "添加系统用户表",notes = "添加系统用户表")
    @PostMapping(value = "/insert")
    public Result insert(SysUserSaveBO saveBO,String password) {
        return sysUserService.add(saveBO,password);
    }

    @SysLogs(value = "修改用户状态")
    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改状态",notes = "修改状态")
     @ApiImplicitParams({
             @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
             ,@ApiImplicitParam(name = "status",value = "状态 0启用，1冻结、2删除",required = true,paramType = "query", dataType = "Integer")
     })
     public Result updateStatus(Long id, Integer status){
         SysUserDTO dto = new SysUserDTO();
         dto.setId(id);
         dto.setStatus(status);
        boolean flag = sysUserService.updateById(dto);
        if(!flag){
            return new Result<>(CodeEnum.FAIL_100008);
        }
        if(status == 1){//冻结的话要删除session
            //去除session
            sysUserService.resetSession(id);
        }
         return new Result<>();
     }

    @SysLogs(value = "删除用户")
    @ApiOperation(value = "删除系统用户表",notes = "删除系统用户表")
    @ApiImplicitParam(name = "id",value = "系统用户表id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id){
        if(null == id){
            return new Result<>(CodeEnum.FAIL_100002 );
        }
        boolean flag = sysUserService.deleteById(id);
        //去除session
        sysUserService.resetSession(id);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<SysUserDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }
        SysUserDTO dto = sysUserService.selectById(id);
        return new Result<>(dto);
    }

    @ApiOperation(value = "系统用户表列表",notes = "系统用户表列表")
    @PostMapping("/queryPageList")
    public Result<Page<SysUserDTO>> queryPageList(SysUserBO bo){
        Wrapper<SysUserDTO> wrapper = new EntityWrapper<>();
        if (bo.getStatus() != null){
            wrapper.eq("status", bo.getStatus());
        }
        //wrapper.eq("user_type", bo.getUserType());
        if (StrUtils.isNotEmpty(bo.getStartDate())){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (StrUtils.isNotEmpty(bo.getEndDate())){
            wrapper.le("create_time", bo.getEndDate());
        }
        if(StrUtils.isNotEmpty(bo.getMobile())){
            wrapper.eq("mobile", bo.getMobile());
        }
        if(StrUtils.isNotEmpty(bo.getAccount())){
            wrapper.eq("account", bo.getAccount());
        }
        if(StrUtils.isNotEmpty(bo.getName())){
            wrapper.like("name", bo.getName());
        }
        Page<SysUserDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = sysUserService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @ApiOperation(value = "用户同步到中台",notes = "用户同步到中台")
    @PostMapping("/syncUser")
    public Result syncUser() throws Exception {
        log.info("syncUser-------------------------start");
        Wrapper<SysUserDTO> wrapper = new EntityWrapper<>();
        SysUserKeyVO users = null;
        List<SysUserDTO> sysUserDTOList = sysUserService.selectList(wrapper);
        if(null != sysUserDTOList && sysUserDTOList.size() > 0){
            List<SysUserKeyVO> usersList = new ArrayList<>();
            for(SysUserDTO sysUserDTO : sysUserDTOList){
                users = new SysUserKeyVO();
                users.setPhone(sysUserDTO.getMobile());
                usersList.add(users);
            }
            log.info("sysUserList-------------------------"+usersList.toString());
            String jsonStr = JSONUtil.toJsonStr(usersList);
            String key = AESUtil.encrypt(jsonStr, ZTConstant.ZT_CONFIG_CLIENTKEY);
            int i = RandomUtils.nextInt(1000000, 10000000);
            String nonceStr = "" + System.currentTimeMillis() + i;
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String sign = SignUtils.createSign(ZTConstant.ZT_CONFIG_APPID, timestamp, nonceStr, key, ZTConstant.ZT_CONFIG_CLIENTKEY);
            try {
                String res = HttpUtil.createPost(ZTConstant.ZT_CONFIG_SYNCUSER_PATH)
                        .header("appId", ZTConstant.ZT_CONFIG_APPID)
                        .header("nonce", nonceStr)
                        .header("timestamp", timestamp)
                        .header("sign", sign)
                        .header("TENANT-ID", ZTConstant.ZT_CONFIG_TENANTID)
                        .form("key", key)
                        .execute().body();
                Object code = JSONObject.parseObject(res).get("code");
                log.info("res-------------------------"+res);
                log.info("code-------------------------"+code);
                if (ObjectUtil.equals(code, 0)) {
                    return new Result<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new Result<>(CodeEnum.FAIL);
            }
        }
        return new Result<>();
    }
}
